﻿module Sustainalytics.Tools.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class ToolsController {

        private toolsService: any;
        public selectedFile: any;

        public loading: boolean;
        public $scope: ng.IScope;
        public $rootScope: any;
        public processEntireFile: boolean;
        public lastSyncDate: Date;

        constructor(
            $scope: ng.IScope,
            $rootScope,
            $q: ng.IQService,
            $location: ng.ILocationService,
            $http: ng.IHttpService,
            ToolsService,
            private notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin) {

            $scope['tools'] = this;

            this.$scope = $scope;
            this.$rootScope = $rootScope;
            this.toolsService = ToolsService;


            this.getLastSyncDate();
        }

        public selectFile($files) {
            this.selectedFile = $files[0];
        }

        private getLogData(logHeading: string, rawMessage: string): string {
            return rawMessage.length == 0 ? "" :
                logHeading + "\n" + (rawMessage.length > 500 ? rawMessage.substr(0, 500) + "...\n" : rawMessage);
        }

        private getErrorMessage(errorStatusCode: number) {
            var errorMessage = "";

            switch (errorStatusCode) {
                case 1000:
                    errorMessage = "Unexpected error encountered on the server while trying to process the uploaded file!";
                    break;
                case 2000:
                    errorMessage = "The uploaded file is invalid!";
                    break;
                default:
                    errorMessage = "There was an error encountered while trying to upload the file selected!";
            }

            return errorMessage;
        }

        public importEsgRatings() {
            if (this.selectedFile) {
                this.$rootScope.loading = true;

                var fileReader = new FileReader();
                fileReader.onload = (rootScope => {
                    return e => this.toolsService.importEsgRatings(e.target.result, this.selectedFile.type)
                        .then(response => // succes handler
                            alert(this.getLogData("Errors:", response.data.importLogs.errors) +
                                this.getLogData("Warnings:", response.data.importLogs.warnings) +
                                this.getLogData("Info:", response.data.importLogs.info))
                        , response => alert(this.getErrorMessage(response.data.errorStatusCode))/* error handler*/)
                        .finally(() => rootScope.loading = false);
                })(this.$rootScope);

                fileReader.readAsArrayBuffer(this.selectedFile);
            }
        }

        public importEsgFocusThreshods(isPercentile: boolean) {
            var ctx = this;
            if (!ctx.selectedFile) return;
            ctx.$rootScope.loading = true;
            var promis = ctx.toolsService.importEsgFocusThresholds(ctx.selectedFile, isPercentile);
            promis.then(a => {
                alert("Import succesfull");
                ctx.$rootScope.loading = false;
            }, e => {
                ctx.notificationFactory.error("", "There was an error on parsing a new esg thresholds excel");
                if (e.data.errors) {
                    console.log(e.data.errors);
                };


                ctx.$rootScope.loading = false;
            });

        }

        public importClaims() {
            if (this.selectedFile) {
                this.$rootScope.loading = true;

                var self = this;

                var promise = self.toolsService.importClaims(self.selectedFile, self.processEntireFile);
                promise.then((data: any) => {
                    var errors = data.data.importLogs.errors;
                    if (errors == null || errors == undefined || errors == '') {
                        alert("Import Successfull!");
                    }
                    else {
                        alert(this.getLogData("Errors:", errors));
                    }
                    self.$rootScope.loading = false;
                }, e => {
                    self.notificationFactory.error("", "There was an error on parsing the claims excel");
                    if (e.data.errors || e.data.errorStatusCode) {
                        console.log(e.data.errors != undefined ? e.data.errors : 'Error status code: ' + e.data.errorStatusCode);
                    };


                    self.$rootScope.loading = false;
                });
            }
        }

        private getLastSyncDate(): ng.IPromise<Date> {
            var ctx = this;
            var promise = ctx.toolsService.lastSyncDate();
            promise.then(
                (syncDate: string) => {
                    var sDate = new Date(syncDate);
                    if (sDate.getTime() > 0)
                        ctx.lastSyncDate = sDate;
                }
            );

            return promise;
        }
    }


    // register controller with Tools Angular module
    var mod = angular.module(toolsAdminModuleName);

    mod.controller('ToolsController',
        ['$scope', '$rootScope', '$q', '$location', '$http', 'ToolsService', 'notificationFactory', 'staticObjectsAdmin', ToolsController]);
}